package cn.dao789.mvvm;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import android.app.Application;
import cn.dao789.model.UserModel;

/**
 * MVVM架构中的ViewModel
 * 负责数据的存储和处理，并通过LiveData将数据变化通知给View
 */
public class UserViewModel extends AndroidViewModel {
    // 使用LiveData包装UserModel，实现数据变化的自动通知
    private MutableLiveData<UserModel> userLiveData;
    
    public UserViewModel(Application application) {
        super(application);
        // 初始化LiveData和Model
        userLiveData = new MutableLiveData<>();
        userLiveData.setValue(new UserModel("3", "MVVM用户", "mvvm@example.com"));
    }
    
    // 获取用户LiveData对象，供View观察
    public MutableLiveData<UserModel> getUserLiveData() {
        return userLiveData;
    }
    
    // 处理保存用户的业务逻辑
    public void saveUser(String username, String email) {
        // 验证输入
        if (username == null || username.isEmpty()) {
            username = "未命名用户";
        }
        
        if (email == null || email.isEmpty()) {
            email = "noemail@example.com";
        }
        
        // 获取当前用户数据并更新
        UserModel currentUser = userLiveData.getValue();
        if (currentUser != null) {
            currentUser.setUsername(username);
            currentUser.setEmail(email);
            // 更新LiveData，触发UI更新
            userLiveData.setValue(currentUser);
        }
    }
}